﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Chromium;
using Chromium.WebBrowser;
using Kugar.UI.RazorUI.CefEngine;
using NetDimension.NanUI;

namespace Kugar.UI.RazorUI
{
    public static class RazorUIEngine
    {
        public static void Init()
        {
            if (Bootstrap.Load(setting => { setting.Locale = "zh-CN"; }, line =>
            {
                line.AppendSwitch("disabled-web-security");
            }))
            {
                RegisterRazorResources(AppDomain.CurrentDomain.BaseDirectory );
                //Bootstrap.RegisterAssemblyResources(typeof(CefRazorFormBase).Assembly,domainName:"res.razorui.local");
                Bootstrap.RegisterFolderResources(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"Views"), domainName: "file.razorui.local");
            }
        }

        /// <summary>
        /// 打开一个窗体,并启动Application.Run
        /// </summary>
        /// <param name="url"></param>
        public static void Run(string url)
        {
            Chromium.CfxRuntime.ExecuteProcess();
            
            var frm=new RazorUIForm(url);
            //frm.Show();

            //Application.Run(frm);
            
            Application.Run(frm);

            CfxRuntime.Shutdown();

            Application.Exit();
        }

        public static void Open(string url)
        {
            var frm = new RazorUIForm(url);
  
            frm.Show();
        }

        private static void RegisterRazorResources(string path, string domainName = "assets.razor.local")
        {
            var factory = new CfxSchemeHandlerFactory();


            factory.Create += (_, args) =>
            {

                if (args.SchemeName == "http" && args.Browser != null)
                {
                    
                    var wb = BrowserCore.GetBrowser(args.Browser.Identifier);
                    var handler = new RazorResourceHandler(path, wb,args.Frame, domainName);
                    args.SetReturnValue(handler);
                }
            };

            Bootstrap.RegisterCustomScheme("http", domainName, factory);

        }
    }
}
